//
//  XYSDKManager.m
//  XYRTCEngineSimpleDemo
//
//  Created by 高超 on 2021/11/5.
//

#import "XYSDKManager.h"

@interface XYSDKManager ()<NemoSDKDelegate>

@property (nonatomic, assign) BOOL isInitSDK;

@property (nonatomic, strong) NSDictionary *errorCodeDic;

@property (nonatomic, strong) NemoRosters *currentRoster;

@end

@implementation XYSDKManager


+ (XYSDKManager *)share {
    static XYSDKManager *sdk = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sdk = [[XYSDKManager alloc] init];
    });
    return sdk;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSString *errorPath = [[NSBundle mainBundle] pathForResource:@"xyErrorCode" ofType:@"json"];
        NSString *errrorString = [NSString stringWithContentsOfFile:errorPath encoding:NSUTF8StringEncoding error:nil];
        NSError *error = nil;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[errrorString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
        _errorCodeDic = dic[@"code"];
    }
    return self;
}

#pragma mark - NemoSDK
- (void)createSDK:(NSString *)enterpriseId
         clientID:(NSString *)clientID
     ClientSecret:(NSString *)ClientSecret
    serverAddress:(NSString *)serverAddress {
    //初始化
    XYSettings *settings = [XYSettings settings];
    settings.extID = enterpriseId;
    settings.clientID = clientID;
    settings.clientSecret = ClientSecret;
    if ([serverAddress containsString:@":"]) {
        settings.server = [serverAddress componentsSeparatedByString:@":"].firstObject;
        settings.httpsPort = [serverAddress componentsSeparatedByString:@":"].lastObject;
    } else {
        settings.server = serverAddress;
    }
    [NemoSDK sharedInstance].delegate = self;
    [[NemoSDK sharedInstance] shareNemoSessionSettings:settings];
    self.isInitSDK = YES;
}

- (void)xylinkLogin:(NSString *)account password:(NSString *)password {
    if (self.isInitSDK) {
        if ([NemoSDK sharedInstance].isLogon) {
            [XYHUDManager showBriefToast:@"请不要重复登录"];
        } else {
            [XYHUDManager showLoading];
            [[NemoSDK sharedInstance] loginXYLinkAccount:account password:password];
        }
    } else {
        [XYHUDManager showBriefToast:@"未初始化SDK"];
    }
}

- (void)login:(NSString *)account userName:(NSString *)userName enterpriseID:(NSString *)enterpriseID {
    if (self.isInitSDK) {
        if ([NemoSDK sharedInstance].isLogon) {
            [XYHUDManager showBriefToast:@"请不要重复登录"];
        } else {
            [XYHUDManager showLoading];
            [[NemoSDK sharedInstance] loginExternalAccount:account userName:userName enterpriseId:enterpriseID];
        }
    } else {
        [XYHUDManager showBriefToast:@"未初始化SDK"];
    }
}

- (void)joinMeeting:(NSString *)number password:(NSString *)password {
    if ([NemoSDK sharedInstance].isLogon) {
        [XYHUDManager showLoading];
        [[NemoSDK sharedInstance] makeCall:number password:password config:nil];
    } else {
        [XYHUDManager showBriefToast:@"当前未登录"];
    }
}

- (void)logout {
    if ([NemoSDK sharedInstance].isLogon) {
        [[NemoSDK sharedInstance] logout];
    } else {
        [XYHUDManager showBriefToast:@"当前未登录"];
    }
}

- (UIViewController*)currentViewController{
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (YES) {
        NSLog(@"%s vc = %@", __FUNCTION__, vc);
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
            
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
            
        } else if (vc.presentedViewController) {
            vc = vc.presentedViewController;
            
        } else {
            break;
        }
    }
    return vc;
}

#pragma mark - Lazy
- (XYMeetingViewController *)meetingVC {
    if (!_meetingVC) {
        _meetingVC = [[XYMeetingViewController alloc] init];
        _meetingVC.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return _meetingVC;
}

#pragma mark - NemoSDKDelegate
- (void)nemoSDKDidLoginResult:(XYUser *)user success:(BOOL)success {
    [XYHUDManager hideToast];
    if (success) {
        self.user = user;
        [XYHUDManager showBriefToast:@"登录成功"];
    } else {
        [XYHUDManager showBriefToast:_errorCodeDic[user.error]?:user.error];
    }
}

- (void)nemoSDKDidLogoutState:(BOOL)success {
    if (success) {
        self.user = nil;
        [XYHUDManager showBriefToast:@"退出登录成功"];
    }
}

- (void)nemoSDKDidCall:(NSString *)number stateChanged:(NemoCallState)callState reason:(NSString *)reason {
    [XYHUDManager hideToast];
    switch (callState) {
        case NemoCallState_Connecting:
        {
            NSLog(@"Connecting...");
        }
            break;
        case NemoCallState_Connected:
        {
            [[self currentViewController] presentViewController:self.meetingVC animated:YES completion:nil];
            self.meetingVC.roomLabel.text = number;
        }
            break;
        case NemoCallState_DisConnected:
        {
            [self.meetingVC dismissViewControllerAnimated:YES completion:^{
                self.meetingVC = nil;
            }];
        }
            break;
            
        default:
            break;
    }
}

- (void)nemoSDKDidRosterChanged:(NemoRosters *)rosters {
    if (_currentRoster.peopleRosters.count != rosters.peopleRosters.count) {
        NSArray *people = rosters.peopleRosters;
        if (rosters.peopleRosters.count > 6) {
            people = [rosters.peopleRosters subarrayWithRange:NSMakeRange(0, 6)];
        }
        NSMutableArray <NemoCustomLayoutInfo *>*reqArray = [NSMutableArray arrayWithCapacity:people.count];
        for (NemoRosterInfo *info in people) {
            NemoCustomLayoutInfo *layout = [[NemoCustomLayoutInfo alloc] init];
            layout.participantId = info.participantId;
            layout.resolution = NemoVideoResolution_360P;
            layout.priority = NemoLayoutPriority_Normal;
            layout.quality = NemoVideoQuality_Normal;
            [reqArray addObject:layout];
        }
        [[NemoSDK sharedInstance] setCustomLayout:reqArray];
    }
    _currentRoster = rosters;
}

- (void)nemoSDKDidVideoChanged:(NSArray<NemoLayout *> *)videos {
    [self.meetingVC videoChange:videos];
}

- (void)nemoSDKDidError:(NSString *)code message:(NSString *)message {
    [XYHUDManager hideToast];
    if ([self.errorCodeDic.allKeys containsObject:code]) {
        [XYHUDManager showBriefToast:self.errorCodeDic[code]];
    } else {
        [XYHUDManager showBriefToast:[NSString stringWithFormat:@"%@ %@",code,message]];
    }
}

@end
